const fs = require("fs");
const { Window, Monitor } = require("node-screenshots");

const appNames = ["Code", "Google Chrome", "Microsoft Teams", "Microsoft Edge", "zoom.us", "腾讯会议"];

function captureAppChrome(filePath) {
  return captureApp("Google Chrome", filePath);
}
const captureApp = async (appName, filePath) => {
  const windows = Window.all();
  let appWindow = null;
  for (let index = 0; index < windows.length; index++) {
    const item = windows[index];
    if (item.title !== "Item-0" && appName === item.appName) {
      appWindow = item;
      break;
    }
  }

  if (!appWindow) return null;

  return await saveImage(filePath, appWindow);
}
const captureMonitor = async (filePath) => {
  let monitor = Monitor.fromPoint(100, 100);
  return await saveImage(filePath, monitor);
}

const imageCrop = async (item) => {
  await item.captureImage().then(async (data) => {
    const newImage = await data.crop(10, 10, 10, 10);
    fs.writeFileSync(`${item.appName}-${item.id}.png`, await newImage.toPng());
  });
}

async function saveImage(filePath, item) {
  const image = await item.captureImage();
  const newImage = await image.crop(0, 240, 3000, 1500);
  const imageData = await newImage.toJpeg();
  if (filePath){
    fs.writeFileSync(filePath, imageData);
  }
  return imageData;
}

module.exports = { captureMonitor, captureApp, captureAppChrome }